package com.neuedu.security.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.neuedu.security.common.Ret;
import com.neuedu.security.entity.SysUser;
import com.neuedu.security.service.ISysUserService;
import com.neuedu.security.utils.JWTUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;

@RestController
@Api(tags = "登录")
public class LoginController {


    @Autowired
    ISysUserService sysUserService;


//    @Autowired
//    PasswordEncoder passwordEncoder;

    /**
     *
     * @param username    admin
     * @param password    123456      asdfasdfasdfasdfsadfasdfsadfsadfsadfasf
     * @return
     */
    @ApiOperation("登录获取token字符串")
    @GetMapping("/login")
    public Ret<String> login(String username, String password, HttpServletResponse response) throws Exception {


        String token = null;
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("user_name",username);

        SysUser user = sysUserService.getOne(queryWrapper);
        Ret ret = null;
        if(user != null){
            //TODO 验证密码
//            passwordEncoder.matches(password,user.getPassword())

//            user.setLoginDate(LocalDateTime.now());
            //调用update的方法

            user.setPassword(password);
            token = JWTUtils.generator(user);
            ret = Ret.ok(token);
        }else{

            //40
//            response.sendError(500,"用户名或者密码错误");
            ret = Ret.fail("用户名或者密码错误");
        }

        return  ret;


    }






}
